package edu.zjut.hjg.saas.kwmp.web.interceptor;

import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.SESSION_NAME_USER;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import edu.zjut.hjg.saas.biz.support.RoleName;
import edu.zjut.hjg.saas.kwmp.web.model.UserSession;

/**
 * 用户权限拦截器
 *
 * @author hjg
 */
public class UserPermissionInterceptor extends HandlerInterceptorAdapter {

    private static final String ENCODE     = "UTF-8";
    private static final String LOGIN_PAGE = "/login/index.htm";

    private RoleName            role;

    public void setRole(RoleName role) {
        this.role = role;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        UserSession session = (UserSession) request.getAttribute(SESSION_NAME_USER);
        String loginUrl = LOGIN_PAGE + "?toUrl=" + getEncodedTargetUrl(request);
        if (session == null) {
            // 未登录
            response.sendRedirect(loginUrl);
            return false;
        }
        if (role == null) {
            role = RoleName.PARENT;
        }
        switch (role) {
            case TEACHER:
                if (session.isParent()) {
                    response.sendRedirect(loginUrl);
                    return false;
                }
                break;
            case ADMIN:
                if (!session.isAdmin()) {
                    response.sendRedirect(loginUrl);
                    return false;
                }
                break;
            default:
        }
        return true;
    }

    private String getEncodedTargetUrl(HttpServletRequest request) {
        StringBuffer buff = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString != null) {
            buff.append("?" + queryString);
        }
        try {
            return URLEncoder.encode(buff.toString(), ENCODE);
        } catch (UnsupportedEncodingException e) {
            return buff.toString();
        }
    }
}
